import React, { ReactElement, useEffect, useState } from 'react';
import { View } from 'react-native';
import { NavigationScreenProps, ScrollView } from 'react-navigation';

import styles from './style';
import Notch, { NotchType } from '../../components/Notch';
import Provider, { Store } from './reducer';
import Header from './components/Header';
import { getProductInfo } from './actions';
import Info from './components/Info';
import Footer from './components/Footer';
import Detail from './components/Detail';
import statusBarManager from '../../util/native/statusBarManager';

let localHeaderOpacity = 0;

export default ({ navigation }: NavigationScreenProps): ReactElement => {
  const commodityId = navigation.getParam('commodityId');
  const [headerOpacity, setHeaderOpacity] = useState(0);

  useEffect((): (() => void) => {
    setTimeout((): void => {
      getProductInfo(commodityId);
    }, 200);

    const willFocusSubscription = navigation.addListener(
      'willFocus',
      (): void => {
        if (localHeaderOpacity > 0.5) {
          statusBarManager.setBarStyle('dark-content', true);
        } else {
          statusBarManager.setBarStyle('light-content', true);
        }
      }
    );

    return (): void => {
      setHeaderOpacity(0);
      localHeaderOpacity = 0;
      willFocusSubscription.remove();
    };
  }, [commodityId, navigation]);

  return (
    <Provider>
      <Store.Consumer>
        {(res): ReactElement => {
          const { state } = res;
          const { isShowSkus } = state;

          return (
            <Notch style={styles.container} type={NotchType.Bottom}>
              <ScrollView
                scrollEventThrottle={17}
                // stickyHeaderIndices={[1]}
                style={styles.content}
                onScroll={(e): void => {
                  const offset = e.nativeEvent.contentOffset.y;
                  if (offset < 100) {
                    setHeaderOpacity(offset / 100);
                    localHeaderOpacity = offset / 100;
                  } else {
                    setHeaderOpacity(1);
                    localHeaderOpacity = 1;
                  }
                }}
              >
                <Info />
                <Detail />
              </ScrollView>
              <Header opacity={headerOpacity} />
              <Footer />
              {isShowSkus && <View style={styles.background} />}
            </Notch>
          );
        }}
      </Store.Consumer>
    </Provider>
  );
};
